﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using SYBOQry = Texfina.BOQry.Sy;
using SYBOMnt = Texfina.BOMnt.Sy;
using System.IO;

namespace RH
{
   public partial class wfConfHoraMnt : EditPage 
   {

      /// <summary>
      /// Guarda el estado de un DataTable, usado para llenar los dropdownlist.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourceDrop
      {
         get { return (DataTable)this.ViewState["_dsDrop"]; }
         set { this.ViewState["_dsDrop"] = value; }
      }

      public static int _GRDLIST_IDHORA = 2;
      public static int _GRDLIST_STIDPERSONAL = 5;
      public static int _GRDLIST_STANULADO = 8;

      protected void Page_Load(object sender, EventArgs e)
      {
           if (this.IsPostBack){
               this.LoadInPostBack();
               return;}
           this.LoadData();
      }

      public override void LoadInPostBack()
      {
         this.RegisterGeneralScripts();
      }

      public override void LoadInitialSettings()
      {
         this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
         this.SetInitialTitle("Configuracion de Importacion de Hora");
      }

      public override void LoadListControls()
      {
         EHora objE = new EHora();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Hora));
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         this.DataSourceDrop = objBO.GetList(objE);
         
      }


      public override void DataToControls()
      {
         EConfigHora objE = new EConfigHora();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(SYBOQry.ConfigHora));
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString() ;
         DataTable dt = objBO.GetList(objE);
         this.GridSetDataBinding(grdList, dt);

      }
      
      protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
      {
            
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_SAVE:
            case ConstMenuToolbarValue.BUTTON_SAVENEW:
               if (this.FormEditAction != FormEditAction.Delete)
                  this.SaveData(e.Item.Value);
               else
                  this.DeleteData();
               break;
            case ConstMenuToolbarValue.BUTTON_EXIT:
               this.Response.Redirect("wfPrestamoBnd.aspx");
               break;
         }
      }

      public override void RegisterGeneralScripts()
      {
         StringBuilder sb = new StringBuilder();
        
         sb.AppendLine("function validateEditForm(key){");
         sb.AppendLine("var gv = document.getElementById('"+ grdList.ClientID +"');");
         sb.AppendLine("if(gv == null){");
         sb.AppendLine("   alert('No existen datos para Guardar');");
         sb.AppendLine("   return false;}");
         sb.AppendLine("var rbs = gv.getElementsByTagName('input');");
         sb.AppendLine("var flag = 0;");  
         sb.AppendLine("for (var i = 0; i < rbs.length; i++) {");  
         sb.AppendLine("   if (rbs[i].type == 'radio') {");  
         sb.AppendLine("      if (rbs[i].checked) {");
         sb.AppendLine("           flag = 1;");  
         sb.AppendLine("           break;");
         sb.AppendLine("      }");  
         sb.AppendLine("   }");  
         sb.AppendLine("}");
         sb.AppendLine("if (rbs.length == 0) {");
         sb.AppendLine("   alert('No existen datos para Guardar');");
         sb.AppendLine("   return false;");
         sb.AppendLine("}");
         sb.AppendLine("if (flag == 0) {");
         sb.AppendLine("   alert('Seleccione el campo para el codigo del personal');");  
         sb.AppendLine("   return false;");
         sb.AppendLine("}");
         sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
         sb.AppendLine("}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
      }

      protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               DropDownList ddl = (DropDownList)e.Row.FindControl("ddlidHora");
               WebHelper.LoadListControl(ddl,DataSourceDrop, "dsHora", "idHora", true, true);
               WebHelper.ListControlSetValue(ddl, e.Row.Cells[_GRDLIST_IDHORA].Text);
               RadioButton rdb = (RadioButton)e.Row.FindControl("rdbidPersonal");
               if (e.Row.Cells[_GRDLIST_STIDPERSONAL].Text == ConstFlagEstado.ACTIVADO)
                  rdb.Checked = true;
            }
      }
      
      public override void SaveData(String key)
      {
         if (this.ValidateData() == false)
            return;

         IEntityBase objE = (IEntityBase)this.CreateEntitySet();
         IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(SYBOMnt.ConfigHora));

         String[] strRet = objPro.UpdateData(objE);
         String strMsg = "";
         strMsg = "Se ha modificado la configuracion.";

         this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, strMsg, "");
      }

      public override void DeleteData()
      {
         IEntityBase objE = (IEntityBase)this.CreateEntitySet();
         IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(SYBOMnt.ConfigHora));
         objPro.DeleteData(objE);

         String strMsg = "";
         strMsg = "Se ha modificado la configuracion.";

         this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, strMsg, "");
      }

      public override Object CreateEntitySet()
      {

         foreach (GridViewRow gvr in grdList.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
               DropDownList ddl = (DropDownList)gvr.FindControl("ddlidHora");
               RadioButton rdb = (RadioButton)gvr.FindControl("rdbidPersonal");
               this.DataSource.Rows[gvr.RowIndex]["idHora"] = ddl.SelectedItem.Value;
               this.DataSource.Rows[gvr.RowIndex]["stIdPersonal"] = rdb.Checked ? ConstFlagEstado.ACTIVADO : ConstFlagEstado.DESACTIVADO;
            }
         }
         
         DataTable dt = (DataTable)this.DataSource;

         IList<EConfigHora> colEHora = new List<EConfigHora>();
         foreach (DataRow drDet in dt.Rows)
         {
            EConfigHora objEDet = DataHelper.CopyDataRowToEntity<EConfigHora>(drDet, typeof(EConfigHora));
            objEDet.EntityState = EntityState.Added;
            colEHora.Add(objEDet);
         }

         EConfigHoraSet objESet = new EConfigHoraSet();
         objESet.ColConfigHora = colEHora;

         return objESet;
      }

      protected void btnDocExcel_Click(object sender, EventArgs e)
      {
         if (this.fuDocExcel.HasFile)
         {
            this.DataSource.Rows.Clear();  
            string strFileName = Server.HtmlEncode(fuDocExcel.FileName);
            string strExtension = Path.GetExtension(strFileName);

            if (strExtension != ".xls" && strExtension != ".xlsx")
            {
               Response.Write("<script>alert('Solo archivos Excel (.xls ó .xlsx)');</script>");
               return;
            }

            string strUploadFileName = "~/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
            fuDocExcel.SaveAs(Server.MapPath(strUploadFileName));
            string strExcelConn = "";

            if (strExtension == ".xls")
            {
               strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties='Excel 8.0;HDR=YES;'";
            }
            else
            {
               strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties='Excel 12.0 Xml;HDR=YES;'";
            }

            DataTable dtExcel = DataHelper.RetrieveData(strExcelConn,"");
            int intindex = 0;
            foreach (DataColumn col in dtExcel.Columns)
            {
               DataRow dr = this.DataSource.NewRow();
               dr["idEmpresa"] = Session[ConstSessionVar.EMPRESA].ToString();
               dr["dsHoraExcel"] = col.ColumnName;
               dr["idHoraExcel"] = intindex;
               dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;
               this.DataSource.Rows.Add(dr);
               intindex++;
            }

            File.Delete(Server.MapPath(strUploadFileName));

            grdList.DataSource = this.DataSource;
            grdList.DataBind();
            
         }
      }

   }
}